﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.WEB.GFMS.Class.MemberShip;
using KPIS.GERP.WEB.GFMS.Class.MemberShip;
using KPIS.GERP.WEB.GFMS.UserService;
using WebMatrix.WebData;

namespace KPIS.GERP.WEB.GFMS.Class
{
	public static class GimsMembership
	{
		private static SimpleMembershipInitializer _initializer;
		private static object _initializerLock = new object();
		private static bool _isInitialized;

        private static void Initialize()
        {
            if (!WebSecurity.Initialized)
            {
                if (!WebSecurity.Initialized)
                {
                    try
                    {
                        // The line below will go to SimpleMembershipInitializer.cs
                        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
                    }
                    catch (Exception exception)
                    {
                        throw new Exception(exception.InnerException.Message, exception);
                    }
                }
            }
        }

		public static int CurrentUserId
		{
			get
			{
				Initialize();
				return WebSecurity.CurrentUserId;
			}
		}

		public static string CurrentUserName
		{
			get
			{
				Initialize();
				return WebSecurity.CurrentUserName;
			}
		}
		
		public static User User
		{
			get
			{
				using(var userService = new UserServiceClient())
				{
					return userService.GetUser(CurrentUserId);
				}
			}
		}

        public static List<User> GetUsers()
        {
            Initialize();

            using (var userService = new UserServiceClient())
            {
                return userService.GetUsers().ToList();
            }
        }

		public static bool IsInRoles(string roles)
		{
			Initialize();

			return true;
		}
        
		public static void AuditLogin(string userLoginMonitorKey)
		{
			Models.Class.CookieUtility.Set("UserLoginMonitorKey", userLoginMonitorKey);
		}

		public static void AuditLogout()
		{
			Models.Class.CookieUtility.Remove("UserLoginMonitorKey");
		}
	}
}